import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import com.mysql.cj.jdbc.Driver;

import org.junit.Test;

public class ConnectionTest {
    //方式一：
    @Test
    public void test1() throws SQLException{
        Driver driver=new Driver();
        String url="jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8";
        Properties info=new Properties();
        info.setProperty("user", "root");
        info.setProperty("password", "697697");
        Connection con=driver.connect(url, info);
        System.out.println(con);
    }
    //方式二：对方式一的改进，使用反射得到Driver实列，以避免直接使用第三方api
    @Test
    public void test2() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException{
        Class clazz=Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver=(Driver) clazz.newInstance();
        String url="jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8";
        Properties info=new Properties();
        info.setProperty("user", "root");
        info.setProperty("password", "697697");
        Connection con=driver.connect(url, info);
        System.out.println(con);
    }
    //方式三：使用DriverManager代替Driver
    @Test
    public void test3() throws Exception{
        Class clazz=Class.forName("com.mysql.cj.jdbc.Driver");
        Driver driver=(Driver) clazz.newInstance();
        DriverManager.registerDriver(driver);
        System.out.println(DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8", "root", "697697"));
    }
    //方式四：对方式三优化，mysql自动加载
    @Test
    public void test4() throws Exception{
        Class.forName("com.mysql.cj.jdbc.Driver");
        System.out.println(DriverManager.getConnection("jdbc:mysql://localhost:3306/test?serverTimezone=GMT%2B8", "root", "697697"));
    }
    //方式五：使用Properties文件
    @Test
    public void test5() throws Exception{
        InputStream ips=ConnectionTest.class.getClassLoader().getResourceAsStream("info.properties");
        Properties pros=new Properties();
        pros.load(ips);
        Class.forName(pros.getProperty("driverClass"));
        System.out.println(DriverManager.getConnection(
                                                        pros.getProperty("url"),
                                                        pros.getProperty("user"),
                                                        pros.getProperty("password")
                                                        ));
    }
}
